<template>
  <el-card shadow="never">
      <!-- 搜索栏 -->
      <el-form v-show="showSearch" ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input
            v-model="queryParams.dictName"
            placeholder="请输入字典名称"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input
            v-model="queryParams.dictType"
            placeholder="请输入字典类型"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="字典状态" clearable style="width: 240px">
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Refresh" @click="handleRefreshCache">刷新缓存</el-button>
          </el-col>
        </el-row>

      <!-- 数据表格 -->
      <DataTable
        :data="typeList"
        :loading="loading"
        :pagination="paginationConfig"
        :on-page-change="handlePageChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="字典编号" align="center" prop="dictId" />
        <el-table-column label="字典名称" align="center" prop="dictName" :show-overflow-tooltip="true" />
        <el-table-column label="字典类型" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <el-link type="primary" @click="handleDictData(scope.row)">
              {{ scope.row.dictType }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
              {{ scope.row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </DataTable>
    </el-card>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog v-model="open" :title="title" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="form.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, getCurrentInstance, computed } from 'vue';
import { useRouter } from 'vue-router';
import { listType, getType, delType, addType, updateType, refreshCache } from '@/api/system/dict/type';
import { ElMessage, ElMessageBox } from 'element-plus';

defineOptions({
  name: 'Dict',
});

const { proxy } = getCurrentInstance() as any;
const router = useRouter();

const loading = ref(true);
const ids = ref<number[]>([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const typeList = ref<any[]>([]);
const title = ref('');
const open = ref(false);
const dateRange = ref<any[]>([]);

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  dictName: undefined,
  dictType: undefined,
  status: undefined,
});

const form = ref<any>({});

const rules = reactive({
  dictName: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
  dictType: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }],
});

const queryFormRef = ref();
const formRef = ref();

// 分页配置
const paginationConfig = computed(() => ({
  pageNum: queryParams.value.pageNum,
  pageSize: queryParams.value.pageSize,
  total: total.value
}));

// 分页变化处理
const handlePageChange = async (page: number, size: number) => {
  queryParams.value.pageNum = page;
  queryParams.value.pageSize = size;
  return await getList();
};

async function getList() {
  loading.value = true;
  console.log('开始获取字典类型列表，查询参数:', proxy.addDateRange(queryParams.value, dateRange.value));
  try {
    const response = await listType(proxy.addDateRange(queryParams.value, dateRange.value));
    console.log('字典类型列表API返回数据:', response);
    typeList.value = response.rows || response.data?.rows || [];
    total.value = response.total || response.data?.total || 0;
    console.log('设置后的字典类型列表:', typeList.value);
    console.log('设置后的总数:', total.value);
  } catch (error) {
    console.error('获取字典类型列表失败:', error);
  } finally {
    loading.value = false;
  }
}

function cancel() {
  open.value = false;
  reset();
}

function reset() {
  form.value = {
    dictId: undefined,
    dictName: undefined,
    dictType: undefined,
    status: '0',
    remark: undefined,
  };
  formRef.value?.resetFields();
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  dateRange.value = [];
  queryFormRef.value?.resetFields();
  handleQuery();
}

function handleSelectionChange(selection: any[]) {
  ids.value = selection.map((item) => item.dictId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加字典类型';
}

function handleUpdate(row?: any) {
  reset();
  const dictId = row?.dictId || ids.value[0];
  getType(dictId).then((response: any) => {
    form.value = response.data;
    open.value = true;
    title.value = '修改字典类型';
  });
}

function submitForm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.dictId != undefined) {
        updateType(form.value).then(() => {
          ElMessage.success('修改成功');
          open.value = false;
          getList();
        });
      } else {
        addType(form.value).then(() => {
          ElMessage.success('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleDelete(row?: any) {
  const dictIds = row?.dictId || ids.value.join(',');
  ElMessageBox.confirm('是否确认删除字典编号为"' + dictIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(function () {
      return delType(dictIds);
    })
    .then(() => {
      getList();
      ElMessage.success('删除成功');
    });
}

function handleExport() {
  proxy.download(
    'system/dict/type/export',
    {
      ...queryParams.value,
    },
    `dict_type_${new Date().getTime()}.xlsx`
  );
}

function handleRefreshCache() {
  refreshCache().then(() => {
    ElMessage.success('刷新成功');
  });
}

function handleDictData(row: any) {
  router.push({ path: '/dict/type/data/' + row.dictId });
}

getList();
</script>

<style scoped lang="scss">
@use '@/styles/common.scss';

// 优化搜索表单间距
.el-form {
  margin-bottom: 8px;
  
  .el-form-item {
    margin-bottom: 12px;
  }
}

// 优化按钮组间距
.el-row.mb8 {
  margin-bottom: 8px;
}

// 彻底清除 Element Plus 默认样式
:deep(.el-row) {
  margin-left: 0 !important;
  margin-right: 0 !important;
  margin: 0 !important;
  
  .el-col {
    padding-right: 0 !important;
  }
}

// 覆盖所有可能的 Element Plus 默认 gutter 样式
:deep(.el-row[style*="margin-left"]) {
  margin-left: 0 !important;
  margin-right: 0 !important;
}
</style>
